package cn.trinea.android.common.util;

import java.io.File;

import android.content.Context;
import android.os.Environment;
import android.os.StatFs;

/**
 * SD卡相关的辅助类
 * oushuhua
 */
public class SDCardUtils {
	private static File mUserDir;

	private static File mImageDir;
	private static File mVoiceDir;
	private static File mVideoDir;
	private static File mCacheDir;

	// 在Application中调用，初始化默认用户dir；登陆成功后调用，初始化用户dir；
	public static void initAppDir(Context context) {
		File sdDir = Environment.getExternalStorageDirectory();
		if (!sdDir.exists()) {
			sdDir = context.getFilesDir();
		}

		mUserDir = new File(sdDir, context.getPackageName() + File.separator + "Default");
		if (!mUserDir.exists()) {
			mUserDir.mkdirs();
		}

		mImageDir = createFileTypeDir("Image");
		mVoiceDir = createFileTypeDir("Voice");
		mVideoDir = createFileTypeDir("Video");
		mCacheDir = createFileTypeDir("Cache");
	}

	// 初始化各文件类型dir
	private static File createFileTypeDir(String dirName) {
		File dir = new File(mUserDir, dirName);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		return dir;
	}

	public static File getUserDir() {
		return mUserDir;
	}

	public static File getImageDir() {
		return mImageDir;
	}

	public static File getVoiceDir() {
		return mVoiceDir;
	}

	public static File getVideoDir() {
		return mVideoDir;
	}

	public static File getCacheDir() {
		return mCacheDir;
	}

	/**
	 * 判断SDCard是否存在,并可写
	 *
	 * @return
	 */
	public static boolean isExternalStorageAvailable() {
		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
			return true;
		}
		return false;
	}


	/**
	 * 获取SD卡路径
	 *
	 * @return
	 */
	public static String getSDCardPath() {
		return Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
	}
	/**
	 * 获取sd卡剩余空间大小
	 *
	 * @return
	 */
	public static long getSDFreeSize() {
		// 取得SD卡文件路径
		File path = Environment.getExternalStorageDirectory();
		StatFs sf = new StatFs(path.getPath());
		// 获取单个数据块的大小(Byte)
		@SuppressWarnings("deprecation")
		long blockSize = sf.getBlockSize();
		// 空闲的数据块的数量
		@SuppressWarnings("deprecation")
		long freeBlocks = sf.getAvailableBlocks();
		// 返回SD卡空闲大小
		// return freeBlocks * blockSize; //单位Byte
		// return (freeBlocks * blockSize)/1024; //单位KB
		return (freeBlocks * blockSize) / 1024 / 1024; // 单位MB
	}

}
